package com.glsc.ngateway.opmanage.service.deposit;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositorySpecialAccount;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.deposit.DepositorySpecialAccountRepository;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class DepositorySpecialAccountService {


    @Resource
    private DepositorySpecialAccountRepository specialAccountRepository;

    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<DepositorySpecialAccount> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<DepositorySpecialAccount> page = specialAccountRepository.findAll(SpecificationUtil.buildSpecification(param, DepositorySpecialAccount.class), pageable);

        return page;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public DepositorySpecialAccount findById(Integer id) {
        Optional<DepositorySpecialAccount> optional = specialAccountRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据类型和日期查询查询特殊账户信息
     *
     * @param type
     * @param date
     * @return
     */
    public DepositorySpecialAccount findByTypeAndDate(String type, String date) {
        List<DepositorySpecialAccount> list = specialAccountRepository.findAll(Example.of(DepositorySpecialAccount.builder().type(type).effectDate(date).build()));
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    public DepositorySpecialAccount save(DepositorySpecialAccount obj) {
        DepositorySpecialAccount account = findByTypeAndDate(obj.getType(), obj.getEffectDate());
        if (Objects.nonNull(account)) {
            obj.setId(account.getId());
        }
        obj.setEffectDate(DateUtil.getNowDateString());
        return specialAccountRepository.save(obj);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        specialAccountRepository.deleteById(id);
    }



}
